#include "TemHum.h"

Am2322::Am2322(unsigned char _pin)
{
    pin = _pin;
    /*
    if ( wiringPiSetup() == -1 )  
    {
        exit( 1 );  
    }
    */
}
int Am2322::read_dht11_dat()  
{  
    unsigned char laststate   = HIGH;  
    unsigned char counter     = 0;  
    unsigned char j       = 0, i;  
    float   f; /* fahrenheit */  

    dht11_dat[0] = dht11_dat[1] = dht11_dat[2] = dht11_dat[3] = dht11_dat[4] = 0;  

    /* pull pin down for 18 milliseconds */  
    pinMode( pin, OUTPUT );  
    digitalWrite( pin, LOW );  
    delay( 18 );  
    /* then pull it up for 40 microseconds */  
    digitalWrite( pin, HIGH );  
    delayMicroseconds( 40 );  
    /* prepare to read the pin */  
    pinMode( pin, INPUT );  

    /* detect change and read data */  
    for ( i = 0; i < MAX_TIMINGS; i++ )  
    {  
        counter = 0;  
        while ( digitalRead( pin ) == laststate )  
        {  
            counter++;  
            delayMicroseconds( 1 );  
            if ( counter == 255 )  
            {  
                break;  
            }  
        }  
        laststate = digitalRead( pin );  

        if ( counter == 255 )  
            break;  

        /* ignore first 3 transitions */  
        if ( (i >= 4) && (i % 2 == 0) )  
        {  
            /* shove each bit into the storage bytes */  
            dht11_dat[j / 8] <<= 1;  
            if ( counter > 16 )  
                dht11_dat[j / 8] |= 1;  
            j++;  
        }  
    }  

    /*  
     * check we read 40 bits (8bit x 5 ) + verify checksum in the last byte  
     * print it out if data is good  
     */  
    int check;
    check = (dht11_dat[0] + dht11_dat[1] + dht11_dat[2] + dht11_dat[3]) & 0xFF; 

    if ( (j >= 40) && (dht11_dat[4] == check ) ) 
    {  
        hum = dht11_dat[0] << 8 | dht11_dat[1];
        tem = dht11_dat[2] << 8 | dht11_dat[3];  
        return 0;
    }
    else  
    {
        return -1;
    }  
}  
int Am2322::read(void)
{
    while(read_dht11_dat() == -1)
        ;
}
float Am2322::getTemperature()
{
    return (float)tem / 10;
}
float Am2322::getHumidity()
{
    return (float)hum / 10;
}
